package it.avantsoft.ls.peer.command;

import it.avantsoft.ls.gl.data.AddressBook;
import it.avantsoft.ls.gl.data.AddressBookManager;
import it.avantsoft.ls.peer.PeerHandler;

public class ABCommand extends PeerCommand {
    private String groupLeaderId;
    private int addressBookID;
    private int addressBookID2;
    private AddressBook addressBook;
    private AddressBook addressBook2;
    private String childId;

    public ABCommand(PeerHandler peerHandler, String groupLeaderId, String childId, int abID, byte[] abByteArray) {
        super(peerHandler);
        this.groupLeaderId = groupLeaderId;
        addressBookID = abID;
        if (addressBookID == 2)
            addressBookID--;
        addressBook = AddressBookManager.getAddressBook(addressBookID);
        addressBook.fromByte(abByteArray);
        addressBook.remove(childId);
        this.childId = childId;
        addressBook2 = null;
        addressBookID2 = -1;

    }

    public ABCommand(PeerHandler peerHandler, String groupLeaderId, String childId, int abID, byte[] labByteArray, int abID2, byte[] cabByteArray) {
        this(peerHandler, groupLeaderId, childId, abID, labByteArray);

        this.addressBookID2 = abID2;
        if (addressBookID2 == 1)
            addressBookID2--;
        this.addressBook2 = AddressBookManager.getAddressBook(addressBookID2);
        addressBook2.fromByte(cabByteArray);

    }

    public void execute() {
        getPeer().setPeerId(childId);
        getPeer().setGroupLeaderId(groupLeaderId);

        getPeer().newAB(addressBook);
        if (addressBookID2 != -1) {
            getPeer().newAB(addressBook2);
        }
    }

    public String toString() {
        return "ABCommand{" +
                "groupLeaderId='" + groupLeaderId + '\'' +
                ", childId='" + childId + '\'' +
                ", addressBookID=" + addressBookID +
                ", addressBook=" + addressBook +
                ", addressBookID=" + addressBookID2 +
                ", addressBook2=" + addressBook2 +
                '}';
    }
}
